<!doctype html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Velocity 3D</title>
    <link rel="stylesheet" href="../include/style.css">
  </head>
  <body>
    <header>
      Example from <a href="http://amzn.com/1430236655?tag=html5anim-20"><em>Foundation HTML5 Animation with JavaScript</em></a>
    </header>
    <canvas id="canvas" width="400" height="400"></canvas>
    <aside>Arrow keys move circle on x and y axis, shift/control key along the z-axis.</aside>

    <script src="../include/utils.js"></script>
    <script src="./classes/ball.js"></script>
    <script>
    window.onload = function () {
      var canvas = document.getElementById('canvas'),
          context = canvas.getContext('2d'),
          ball = new Ball(),
          xpos = 0,
          ypos = 0,
          zpos = 0,
          vx = 0,
          vy = 0,
          vz = 0,
          friction = 0.98,
          fl = 250,
          vpX = canvas.width / 2,
          vpY = canvas.height / 2;

      window.addEventListener('keydown', function (event) {
        switch (event.keyCode) {
        case 38:        //up
          vy -= 1;
          break;
        case 40:        //down
          vy += 1;
          break;
        case 37:        //left
          vx -= 1;
          break;
        case 39:        //right
          vx += 1;
          break;
        case 16:        //shift
          vz += 1;
          break;
        case 17:        //control
          vz -= 1;
          break;
        }
      }, false);

      (function drawFrame () {
        window.requestAnimationFrame(drawFrame, canvas);
        context.clearRect(0, 0, canvas.width, canvas.height);
        
        xpos += vx;
        ypos += vy;
        zpos += vz;
        vx *= friction;
        vy *= friction;
        vz *= friction;
        
        if (zpos > -fl) {
          var scale = fl / (fl + zpos);
          ball.scaleX = ball.scaleY = scale;
          ball.x = vpX + xpos * scale;
          ball.y = vpY + ypos * scale;
          ball.visible = true;
        } else {
          ball.visible = false;
        }
        if (ball.visible) {
          ball.draw(context);
        }
      }());
    };
    </script>
  </body>
</html>
